import { Injectable } from '@nestjs/common';
import { CreateWarehouseDto } from 'src/dto/create-warehouse.dto';
import { UpdateWarehouseDto } from 'src/dto/update-warehouse.dto';
import { Warehouse } from 'src/entity/warehouse.entity';
import { QueryWarehouseDto } from 'src/dto/query-warehouse.dto';
import { parseQueryParams } from 'src/common/utils';
import { Box } from 'src/entity/box.entity';
import axios from 'axios';

@Injectable()
export class WarehouseService {
  create(createWarehouseDto: CreateWarehouseDto) {
    return Warehouse.save({
      ...createWarehouseDto,
    });
  }

  async findAll(pageNum: number, pageSize: number) {
    const [list, count] = await Warehouse.findAndCount({
      skip: (pageNum - 1) * pageSize,
      take: pageSize,
    });

    return { list, count };
  }

  async query(query: QueryWarehouseDto) {
    let qeryBuilder = Warehouse.createQueryBuilder('warehouse');

    let { queryClone, pageNum, pageSize } = parseQueryParams(query, [
      //  'categoryId',
    ]);

    qeryBuilder.where(queryClone);

    // 关联查询
    // if (query.categoryId) {
    //  qeryBuilder
    //    .leftJoinAndSelect('warehouse.category', 'category')
    //    .andWhere('category.id = :categoryId', {
    //      categoryId: query.categoryId,
    //    });
    // }

    qeryBuilder.leftJoinAndSelect('warehouse.boxs', 'boxs');

    qeryBuilder.skip((pageNum - 1) * pageSize);
    qeryBuilder.take(pageSize);

    let [list, count] = await qeryBuilder.getManyAndCount();

    let calcList = [];

    for await (const item of list) {
      let obj = { ...item, boxNumber: 0, stock: 0 };

      for await (const box of item.boxs) {
        // 只计算在库存中的箱子 已出库的不计算
        if (box.status == 1) {
          obj.stock += box.boxNumber;
          obj.boxNumber = obj.boxNumber + 1;
        }
      }

      calcList.push(obj);
    }

    return { list: calcList, count };
  }

  findOne(id: number) {
    return Warehouse.findOneBy({ id });
  }

  update(id: number, updateWarehouseDto: UpdateWarehouseDto) {
    return Warehouse.update(id, { ...updateWarehouseDto });
  }

  remove(id: number) {
    return Warehouse.update(id, { deleteTime: new Date() });
  }

  async exportExcel(id: number) {
    // 查询仓库中所有箱子 并且关联查询商品 SKU
    let queryRunner = Box.createQueryBuilder('box');

    queryRunner.leftJoinAndSelect('box.mercadosku', 'mercadosku');
    queryRunner.leftJoinAndSelect('box.mercadoproduct', 'mercadoproduct');

    queryRunner.where('box.warehouseId = :warehouseId', { warehouseId: id });
    queryRunner.where('box.status = :status', { status: 1 });

    return await queryRunner.getMany();
  }

  async getImageBuffer(imageUrl: string): Promise<Buffer> {
    const response = await axios.get(imageUrl, { responseType: 'arraybuffer' });
    return Buffer.from(response.data, 'binary');
  }
}
